<template>
  <div class="dialog">
    <el-dialog
      title="保养任务配置"
      :visible.sync="showDialog"
      width="55%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-form
        ref="ruleForm"
        label-position="left"
        :model="formData"
        :rules="rules"
        class="el-form"
      >
        <el-form-item label="任务名称：" class="w50p" prop="taskName">
          <el-input
            v-model="formData.taskName"
            :disabled="!canInput"
            clearable
            placeholder="请输入任务名称"
          />
        </el-form-item>
        <el-form-item label="任务模板：" class="w50p" prop="planTaskModelId">
          <el-select
            v-model="formData.planTaskModelId"
            clearable
            filterable
            :disabled="!canInput"
            placeholder="任务模板选择"
          >
            <el-option
              v-for="item of planModelList"
              :key="item.planTaskModelId"
              :label="item.planTaskModelName"
              :value="item.planTaskModelId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务模板归属计划：" class="w50p" prop="planId">
          <el-select
            v-model="formData.planId"
            clearable
            filterable
            :disabled="!canInput"
            placeholder="任务模板归属计划选择"
          >
            <el-option
              v-for="item of planList"
              :key="item.planId"
              :label="item.planName"
              :value="item.planId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配置时间：" class="w50p" prop="startTime">
          <div>
            <el-date-picker
              v-model="formData.startTime"
              :disabled="!canInput"
              type="datetime"
              placeholder="选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable
            />
            <el-date-picker
              v-model="formData.endTime"
              :disabled="!canInput"
              type="datetime"
              placeholder="选择结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable
            />
          </div>
        </el-form-item>
        <el-form-item label="是否需要审核：" class="w50p" prop="whetherExamine">
          <el-select
            v-model="formData.whetherExamine"
            clearable
            filterable
            :disabled="!canInput"
            placeholder="选择是否需要审核"
          >
            <el-option
              v-for="item of whetherExamineList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formData.whetherExamine"
          label="审核时间："
          class="w50p"
          prop="startTime"
        >
          <div>
            <el-date-picker
              v-model="formData.reviewStartTime"
              :disabled="!canInput"
              type="datetime"
              placeholder="选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable
            />
            <el-date-picker
              v-model="formData.reviewEndTime"
              :disabled="!canInput"
              type="datetime"
              placeholder="选择结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable
            />
          </div>
        </el-form-item>
      </el-form>
      <div class="equip-select-box-show-box">
        <div class="equip-select-box-show-title" @click="querShow()">预览全部设备及保养项</div>
      </div>
      <div class="equip-select-box">
        <div class="equip-select-box-left">
          <div class="equip-select-box-left-title">设备列表</div>
          <div class="equip-select-box-left-content">
            <el-tree
              ref="tree"
              :data="checkedEquipments"
              :show-checkbox="false"
              node-key="equipmentCode"
              :default-checked-keys="[]"
              :props="defaultProps"
              @node-click="queryShowHaveChekcList"
            />
          </div>
        </div>
        <div class="equip-select-box-right">
          <el-table
            ref="checkTable"
            highlight-current-row
            :data="checkList"
            stripe
            border
            height="100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="50">
              <template
                slot-scope="scoped"
              >{{ scoped.row.equipmentCheckItemMapperId?scoped.$index+1:'' }}</template>
            </el-table-column>
            <el-table-column prop="checkItemName" label="保养项名称" />
            <el-table-column label="标准值">
              <template slot-scope="scoped">
                <div
                  v-if="scoped.row.checkType==='NUMTYPE'"
                >{{ scoped.row.lowerLimit?'下限:'+scoped.row.lowerLimit+scoped.row.unitName:'' }}{{ scoped.row.upperLimit?'上限:'+scoped.row.upperLimit+scoped.row.unitName:'' }}</div>
                <div v-else>{{ scoped.row.standardValue }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="accessMethod" label="保养方式" />
            <el-table-column prop="checkResult" label="保养结果" />
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
      </div>
    </el-dialog>
    <ShowCheckDialog
      ref="ShowCheckDialog"
      :show-check-list="showCheckList"
      :show.sync="showCheckDialog"
      @closeDialog="showCheckDialog=false"
      @cancelDialog="showCheckDialog=false"
    />
  </div>
</template>

<script>
import maintenanceTaskTemplateApi from "@/api/equip-maintenance-manage/maintenance-task-template";
import maintenancePlanApi from "@/api/equip-maintenance-manage/maintenance-plan";
import maintenanceDataitemApi from "@/api/equip-maintenance-manage/maintenance-dataitem";
import ShowCheckDialog from "../../components/show-check-dialog.vue";
import maintenanceTaskApi from "@/api/equip-maintenance-manage/maintenance-task";
export default {
  name: "",
  components: { ShowCheckDialog },
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: "",
    },
    nowChanceStau: {
      type: String,
      default: "",
    },
    show: {
      type: Boolean,
      default: false,
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      formData: {},
      rules: {
        taskName: [
          {
            required: true,
            message: "请输入任务名称",
            trigger: ["change", "blur"],
          },
        ],
        planId: [
          {
            required: true,
            message: "请任务模板归属计划",
            trigger: ["change", "blur"],
          },
        ],
        whetherExamine: [
          {
            required: true,
            message: "请选择是否需要审核",
            trigger: ["change", "blur"],
          },
        ],
        generateHour: [
          {
            required: true,
            message: "请选择任务自动生成时间",
            trigger: ["change", "blur"],
          },
        ],
      },
      // 任务模板归属计划
      planList: [],
      whetherExamineList: [
        { name: "是", id: true },
        { name: "否", id: false },
      ],
      // 任务审核时间
      generateHourList: [
        { generateHourId: 0, generateHourName: "00:00:00" },
        { generateHourId: 1, generateHourName: "01:00:00" },
        { generateHourId: 2, generateHourName: "02:00:00" },
        { generateHourId: 3, generateHourName: "03:00:00" },
        { generateHourId: 4, generateHourName: "04:00:00" },
        { generateHourId: 5, generateHourName: "05:00:00" },
        { generateHourId: 6, generateHourName: "06:00:00" },
        { generateHourId: 7, generateHourName: "07:00:00" },
        { generateHourId: 8, generateHourName: "08:00:00" },
        { generateHourId: 9, generateHourName: "09:00:00" },
        { generateHourId: 10, generateHourName: "10:00:00" },
        { generateHourId: 11, generateHourName: "11:00:00" },
        { generateHourId: 12, generateHourName: "12:00:00" },
        { generateHourId: 13, generateHourName: "13:00:00" },
        { generateHourId: 14, generateHourName: "14:00:00" },
        { generateHourId: 15, generateHourName: "15:00:00" },
        { generateHourId: 16, generateHourName: "16:00:00" },
        { generateHourId: 17, generateHourName: "17:00:00" },
        { generateHourId: 18, generateHourName: "18:00:00" },
        { generateHourId: 19, generateHourName: "19:00:00" },
        { generateHourId: 20, generateHourName: "20:00:00" },
        { generateHourId: 21, generateHourName: "21:00:00" },
        { generateHourId: 22, generateHourName: "22:00:00" },
        { generateHourId: 23, generateHourName: "23:00:00" },
      ],
      dayList: [
        { dayName: "1天", dayId: 1 },
        { dayName: "2天", dayId: 2 },
        { dayName: "3天", dayId: 3 },
        { dayName: "4天", dayId: 4 },
        { dayName: "5天", dayId: 5 },
        { dayName: "6天", dayId: 6 },
        { dayName: "7天", dayId: 7 },
        { dayName: "8天", dayId: 8 },
        { dayName: "9天", dayId: 9 },
        { dayName: "10天", dayId: 10 },
        { dayName: "11天", dayId: 11 },
        { dayName: "12天", dayId: 12 },
        { dayName: "13天", dayId: 13 },
        { dayName: "14天", dayId: 14 },
      ],
      showDialog: this.show,
      // 该设备的保养项
      checkList: [],
      // 查询所有设备
      mixAllEquipmentList: [],
      // 全选按钮
      checkAll: false,
      isIndeterminate: true,
      // 已经选中的设备
      checkedEquipments: [],
      showCheckList: [],
      showCheckDialog: false,
      // 当前添加的设备
      equipmentCode: "",
      // 任务模板
      planModelList: [],
      // 已经绑定的模板详情
      // getPlanTaskModelList: [],
      // 任务详情
      getTaskInfoList: [],
      defaultProps: {
        label: "equipmentName",
        id: "equipmentCode",
      },
      canInput: false,
    };
  },
  watch: {
    show(v) {
      this.showDialog = v;
    },
    nowChanceStau(v) {
      this.checkList = [];
      this.showCheckList = [];
      this.checkedEquipments = [];
      if (v === "showDetail") {
        // 查询已绑定的保养项和设备
        this.formData = this.editObject;
        // 查询已绑定的保养项和设备
        this.queryTaskInfo(this.formData.taskId);
        this.selectPlan(this.formData.planId);
      }
    },
  },
  created() {
    this.queryPlanList();
    this.queryPlanTaskModelList();
    this.mixQueryEquipment();
  },
  mounted() {},
  methods: {
    // 查询任务详情
    queryTaskInfo(item) {
      var params = {
        taskId: item,
      };
      maintenanceTaskApi.query(params).then((res) => {
        if (res.code === 1) {
          let data = res.data || [];
          this.getTaskInfoList = data["taskEquipmentMapperList"] || [];
          this.showCheckList = [];
          this.checkedEquipments = [];
          if (this.getTaskInfoList.length > 0) {
            for (var i in this.getTaskInfoList) {
              // 选中该已选设备
              var index = this.mixAllEquipmentList.findIndex(
                (d) =>
                  d.equipmentCode === this.getTaskInfoList[i]["equipmentCode"]
              );
              if (index !== -1) {
                this.checkedEquipments.push(this.mixAllEquipmentList[index]);
              }
              // 收集已选保养项
              var src = {
                equipmentCode: this.getTaskInfoList[i]["equipmentCode"],
                equipmentName: this.changeEquipmentNameById(
                  this.getTaskInfoList[i]["equipmentCode"]
                ),
              };
              src["taskCheckItemMapperList"] = [];
              if (
                this.getTaskInfoList[i]["taskCheckItemMapperList"].length > 0
              ) {
                for (var k in this.getTaskInfoList[i][
                  "taskCheckItemMapperList"
                ]) {
                  src["taskCheckItemMapperList"].push(
                    this.getTaskInfoList[i]["taskCheckItemMapperList"][k]
                  );
                }
              }
              this.showCheckList.push(src);
            }
            if (this.showCheckList.length > 0) {
              this.queryHaveCheckList(this.showCheckList[0].equipmentCode);
            }
          }
        }
      });
    },
    // 获取该设备的保养项（包含被选中的）
    queryShowHaveChekcList(data) {
      this.equipmentCode = data.equipmentCode;
      this.queryHaveCheckList(data.equipmentCode);
    },
    // 查询该设备下的保养项
    async queryHaveCheckList(equipmentCode) {
      var key = this.mixAllEquipmentList.findIndex(
        (a) => a.equipmentCode === equipmentCode
      );
      if (key !== -1) {
        if (
          this.mixAllEquipmentList[key]["checkList"] &&
          this.mixAllEquipmentList[key]["checkList"].length > 0
        ) {
          this.checkList = this.mixAllEquipmentList[key]["checkList"];
        } else {
          await maintenanceDataitemApi
            .queryByEquipmentCode({ equipmentCode: equipmentCode })
            .then((res) => {
              if (res.code === 1) {
                var data = res.data || [];
                this.checkList = data;
                this.mixAllEquipmentList[key]["checkList"] = this.checkList;
              }
            });
        }
        if (this.checkList.length > 0) {
          var index = this.showCheckList.findIndex(
            (a) => a.equipmentCode === equipmentCode
          );
          if (index !== -1) {
            var list = [];
            this.checkList.forEach((a) => {
              var k = this.showCheckList[
                index
              ].taskCheckItemMapperList.findIndex(
                (b) =>
                  b.equipmentCheckItemMapperId === a.equipmentCheckItemMapperId
              );
              if (k !== -1) {
                if (
                  this.showCheckList[index].taskCheckItemMapperList[k][
                    "checkResult"
                  ]
                ) {
                  a.checkResult =
                    this.showCheckList[index].taskCheckItemMapperList[k][
                      "checkResult"
                    ];
                }
                list.push(a);
              }
            });
            this.toggleSelection(list);
          }
        }
      }
    },
    // 默认全选
    toggleSelection(rows) {
      if (rows) {
        this.$nextTick(() => {
          rows.forEach((row) => {
            this.$refs.checkTable.toggleRowSelection(row, true);
          });
        });
      } else {
        this.$refs.checkTable.clearSelection();
      }
    },
    // 单个是否勾选该设备下的保养项
    handleSelectionChange(list) {
      this.checkedIdList = [];
      this.checkedIdList = list.map((item) => item.equipmentCheckItemMapperId);
    },
    changeEquipmentNameById(v) {
      var index = this.mixAllEquipmentList.findIndex(
        (item) => item.equipmentCode === v
      );
      if (index !== -1) {
        return this.mixAllEquipmentList[index]["equipmentName"];
      }
    },
    // 显示预览表
    querShow() {
      this.showCheckDialog = true;
    },
    // 选择计划自动填充是否审核和生成时间
    selectPlan(data) {
      if (data) {
        maintenancePlanApi.query({ planId: data }).then((res) => {
          if (res.code === 1) {
            let data = res.data || [];
            this.$set(this.formData, "whetherExamine", data["whetherExamine"]);
            this.$set(this.formData, "generateHour", data["generateHour"]);
          } else {
            this.$message.error(res.msg);
          }
        });
      }
    },
    // 任务模板
    queryPlanTaskModelList() {
      maintenanceTaskTemplateApi.queryList({}).then((res) => {
        if (res.code === 1) {
          let data = res.data || {};
          this.planModelList = data || [];
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 任务模板归属计划
    queryPlanList() {
      maintenancePlanApi.queryList({}).then((res) => {
        if (res.code === 1) {
          let data = res.data || {};
          this.planList = data || [];
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep
  .el-dialog__wrapper
  .el-dialog
  .el-dialog__body
  .el-form
  .el-form-item
  .el-form-item__label {
  min-width: 160px;
}
.equip-select-box {
  display: flex;
  width: 100%;
  min-height: 300px;
  .equip-select-box-left {
    min-width: 160px;
    flex: 1;
    background-color: #c0dbe1;
    padding: 10px;
    margin-right: 10px;
    color: #000;
    .equip-select-box-left-title {
      padding: 0 0 10px 0;
      font-size: 17px;
      text-align: center;
      border-bottom: 1px dashed #e2e2e2;
    }
    .equip-select-box-left-content {
      padding: 10px 0 0;
      max-height: 300px;
      overflow-y: auto;
      overflow-x: hidden;
    }
  }
  .equip-select-box-right {
    flex: 3;
  }
}
::v-deep .el-checkbox {
  padding: 0 0 5px 0;
  color: #fff;
}
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #fff;
}
::v-deep .el-table th {
  color: #000;
  background-color: rgba(120, 182, 193, 0.4) !important;
}
::v-deep .el-table .el-table__row--striped {
  color: #000;
  background-color: rgba(186, 186, 186, 0.4) !important;
}
::v-deep.el-table td,
.el-table th.is-leaf,
.el-table--border,
.el-table--group,
.el-table th.is-leaf {
  border-color: #d3d3d3 !important;
}
::v-deep .el-table th.is-leaf {
  border-color: #d3d3d3 !important;
}
::v-deep .el-table__empty-text {
  color: #000;
}
::v-deep .el-table {
  color: #000;
  position: relative !important;
}
.equip-select-box-show-box {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.equip-select-box-show-title {
  color: #000;
  margin: 10px;
  cursor: pointer;
  font-size: 17px;
  position: relative;
  width: fit-content;
  white-space: nowrap;
  &:after {
    content: "";
    position: absolute;
    bottom: -4px;
    left: 0;
    width: 100%;
    height: 2px;
    z-index: 999;
    background-color: #006e91;
  }
  &:hover {
    color: #006e91;
  }
}
::v-deep .el-tree-node {
  white-space: nowrap;
  outline: 0;
  background-color: #c0dbe1;
  border: #c0dbe1 1px solid;
  margin-top: 0 !important;
}
::v-deep .el-tree-node .el-tree-node__content {
  background-color: #c0dbe1 !important;
}
::v-deep .el-tree-node__label {
  background-color: #c0dbe1 !important;
  color: #000 !important;
}
</style>
